<template>
	<div>
		<main-content
			v-if="pageType === 'i'"
			:tableHeight.sync="tableHeight"
			:otherDependenComponents="otherDependenComponents"
		>
			<template slot="query">
				<el-form
					ref="form"
					:inline="true"
					:model="queryData"
					class="flex-warp-container"
				>
					<el-form-item
						:label="`${$t('common.belong_merchant')}:`"
						class="flex-row-container"
						label-width="77px"
					>
						<merchant-select
							v-model="queryData.merchantId"
							:merchantInfo.sync="merchantObj"
						></merchant-select>
					</el-form-item>
					<el-form-item
						:label="
							`${$t(
								'funds.proxy_member_funds_record.rebate_time'
							)}:`
						"
						class="flex-row-container"
						label-width="77px"
					>
						<el-date-picker
							v-model="searchTime"
							type="daterange"
							range-separator="-"
							:start-placeholder="$t('common.start_date')"
							:end-placeholder="$t('common.end_date')"
							:picker-options="pickerShortcut2"
							:clearable="false"
						></el-date-picker>
					</el-form-item>
					<el-form-item
						:label="
							`${$t(
								'funds.proxy_member_funds_record.issue_time'
							)}:`
						"
						class="flex-row-container"
						label-width="77px"
					>
						<el-date-picker
							v-model="searchGetTime"
							type="daterange"
							range-separator="-"
							:start-placeholder="$t('common.start_date')"
							:end-placeholder="$t('common.end_date')"
							:picker-options="pickerShortcut2"
							:default-time="['00:00:00', '23:59:59']"
							:clearable="true"
						></el-date-picker>
					</el-form-item>
					<el-form-item class="flex-row-container">
						<el-input
							v-model="queryData.inputValue"
							:placeholder="$t('common.please_enter')"
							clearable
							v-symbols
							size="medium"
							@input="forceUpdate"
						>
							<el-select
								slot="prepend"
								v-model="queryData.inputType"
								class="input-with-select"
								:placeholder="$t('common.please_choose')"
							>
								<el-option
									:label="$t('funds.proxy_name')"
									:value="1"
								></el-option>
								<el-option
									:label="
										$t('funds.fund_audit.top_proxy_name')
									"
									:value="2"
								></el-option>
							</el-select>
						</el-input>
					</el-form-item>
					<el-form-item
						:label="
							`${$t(
								'funds.proxy_member_funds_record.parent_proxy_account'
							)}:`
						"
						class="flex-row-container"
						label-width="77px"
					>
						<el-input
							v-model="queryData.parentProxyAccount"
							clearable
							:placeholder="$t('common.please_enter')"
							oninput="value=value.replace(/[\u4E00-\u9FA5]/g ,'')"
							v-symbols
						></el-input>
					</el-form-item>
					<el-form-item
						:label="`${$t('funds.order_no')}:`"
						class="flex-row-container"
						label-width="61px"
					>
						<el-input
							v-model="queryData.orderNo"
							clearable
							:placeholder="$t('common.please_enter')"
							oninput="value=value.replace(/[\u4E00-\u9FA5]/g ,'')"
							v-symbols
						></el-input>
					</el-form-item>
					<el-form-item
						:label="
							`${$t(
								'funds.proxy_member_funds_record.person_rebate_amount'
							)}:`
						"
						class="flex-row-container"
						label-width="77px"
					>
						<el-input
							v-model="queryData.personRebateAmountMin"
							size="medium"
							clearable
							:placeholder="$t('common.minimum')"
							style="width: 130px"
							maxLength="15"
							v-input="{ name: 'onlyTwoNum' }"
							name="personRebateAmountMin"
							@blur="
								handleAmount(
									queryData,
									1,
									'personRebateAmountMin',
									'personRebateAmountMax',
									$t(
										'funds.proxy_member_funds_record.form_search_rebateCheck1'
									)
								)
							"
						></el-input>
						-
						<el-input
							v-model="queryData.personRebateAmountMax"
							size="medium"
							clearable
							:placeholder="$t('common.maximum')"
							style="width: 130px"
							maxLength="15"
							v-input="{ name: 'onlyTwoNum' }"
							name="personRebateAmountMax"
							@blur="
								handleAmount(
									queryData,
									2,
									'personRebateAmountMin',
									'personRebateAmountMax',
									$t(
										'funds.proxy_member_funds_record.form_search_rebateCheck2'
									)
								)
							"
						></el-input>
					</el-form-item>
					<el-form-item
						:label="
							`${$t(
								'funds.proxy_member_funds_record.rebate_amount_point'
							)}:`
						"
						class="flex-row-container"
						label-width="77px"
					>
						<el-input
							v-model="queryData.rebateAmountMin"
							size="medium"
							clearable
							:placeholder="$t('common.minimum')"
							style="width: 130px"
							maxLength="15"
							v-input="{ name: 'onlyTwoNum' }"
							name="rebateAmountMin"
							@blur="
								handleAmount(
									queryData,
									1,
									'rebateAmountMin',
									'rebateAmountMax',
									$t(
										'funds.proxy_member_funds_record.form_team_rebateCheck1'
									)
								)
							"
						></el-input>
						-
						<el-input
							v-model="queryData.rebateAmountMax"
							size="medium"
							clearable
							:placeholder="$t('common.maximum')"
							style="width: 130px"
							maxLength="15"
							v-input="{ name: 'onlyTwoNum' }"
							name="rebateAmountMax"
							@blur="
								handleAmount(
									queryData,
									2,
									'rebateAmountMin',
									'rebateAmountMax',
									$t(
										'funds.proxy_member_funds_record.form_team_rebateCheck2'
									)
								)
							"
						></el-input>
					</el-form-item>
					<el-form-item
						:label="
							`${$t(
								'funds.proxy_member_funds_record.client_state'
							)}:`
						"
						class="flex-row-container"
						label-width="91px"
					>
						<el-select
							v-model="queryData.payoutStatus"
							clearable
							:placeholder="$t('common.select_all')"
							:popper-append-to-body="false"
						>
							<el-option
								v-for="item in withdrawOrderClientStatus"
								:key="item.code"
								:label="item.description"
								:value="item.code"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item :label="$t('agent.agent_level') + ':'">
						<el-select
							v-model="queryData.proxyLevel"
							style="width: 120px"
							clearable
							collapse-tags
							:placeholder="$t('common.all')"
						>
							<el-option
								v-for="item in proxyLevels"
								:key="item.id"
								:label="item.id"
								:value="item.id"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button
							type="primary"
							icon="el-icon-search"
							size="medium"
							@click="search"
						>
							{{ $t('common.search') }}
						</el-button>
						<el-button
							icon="el-icon-refresh-left"
							size="medium"
							@click="reset"
						>
							{{ $t('common.reset') }}
						</el-button>
						<el-button
							v-if="hasPermission('405101')"
							type="warning"
							icon="el-icon-download"
							size="medium"
							:disabled="loading"
							:loading="exportBtnLoading"
							@click="handleExportExcel"
						>
							{{ $t('common.export') }}
						</el-button>
						<el-button
							type="success"
							icon="el-icon-sort"
							:disabled="loading"
							size="medium"
							@click="openColSettings()"
						>
							{{ $t('common.row_set') }}
						</el-button>
					</el-form-item>
				</el-form>
			</template>
			<template slot="content">
				<el-table
					v-loading="loading"
					ref="elTable"
					border
					size="mini"
					show-summary
					:data="tableData"
					style="width: 100%"
					class="small-size-table"
					:max-height="tableHeight"
					:key="headKey"
					v-bind="$attrs"
					v-on="$listeners"
					:cell-class-name="cellClassName"
					:header-cell-class-name="cellClassName"
					:header-cell-style="getRowClass"
					element-loading-spinner="el-icon-loading"
					highlight-current-row
					:summary-method="
						(val) => handleRow(val, subSummary, totalSummary)
					"
				>
					<el-table-column
						v-for="(item, index) in newCol"
						:key="`col_${index}`"
						:prop="newCol[index].prop"
						:align="item.alignCenter"
						:label="item.label"
						:min-width="item.minWidth"
						:fixed="item.isFixed"
						:show-overflow-tooltip="item.isShowTip"
					>
						<!-- 通过插槽为表头绑定mousedown和dragover方法 -->
						<template slot="header" slot-scope="{ column, $index }">
							<span
								@mousedown="
									handleMounseDown($event, column, $index)
								"
								@dragover="
									handleDragover($event, column, $index)
								"
							>
								{{ item.label }}
							</span>
						</template>
						<template slot-scope="{ row }">
							<Copy
								v-if="item.solt === 'copySolt'"
								:title="row[newCol[index].prop]"
								:copy="copy"
							>
								{{ row[newCol[index].prop] }}
							</Copy>
							<span v-if="item.solt === 'accountStatusSolt'">
								<span
									v-if="row.loginLockStatus === 1"
									class="disableRgba"
								>
									{{ $t('common.login_lock_status') }}
								</span>
								<span
									v-if="row.accountLockStatus === 1"
									class="deleteRgba"
								>
									{{ $t('common.account_lock_status') }}
								</span>
								<span
									v-if="
										row.loginLockStatus === 0 &&
											row.accountLockStatus === 0
									"
									class="normalRgba"
								>
									{{ $t('common.account_status_normal') }}
								</span>
							</span>
							<span v-if="item.solt === 'amountSolt'">
								<p
									v-if="item.solt === 'soltColor'"
									:style="
										handleNumberColor(
											row[newCol[index].prop]
										)
									"
								>
									{{
										handleTotalNumber(
											row.currency,
											row[newCol[index].prop]
										)
									}}
								</p>
								<p v-else>
									{{ handleCurrency(row.currency) }}
									{{
										handleNumber(
											row.currency,
											row[newCol[index].prop]
										)
									}}
								</p>
							</span>
							<span v-if="item.solt === 'auditSolt'">
								{{
									row.audit1Desc
										? `${$t(
												'funds.proxy_member_funds_record.frirst_audit'
										  )}：${row.audit1Desc}`
										: '-'
								}}
								<br v-show="row.audit2Desc" />
								{{
									row.audit2Desc
										? `${$t(
												'funds.proxy_member_funds_record.second_audit'
										  )}：${row.audit2Desc}`
										: '-'
								}}
							</span>
							<span v-if="item.solt === 'actionSolt'">
								<el-button
									type="primary"
									size="medium"
									@click="openDetail(row)"
								>
									{{ $t('common.check_detail') }}
								</el-button>
							</span>
							<div v-if="item.solt === 'filterType'">
								{{
									typeFilter(
										row[newCol[index].prop],
										'rebateArrList'
									)
								}}
							</div>
							<span v-if="item.solt === 'defaultSolt'">
								{{ row[newCol[index].prop] || '-' }}
							</span>
						</template>
					</el-table-column>
				</el-table>
				<!-- 分页 -->
				<el-pagination
					v-show="!!total"
					class="pageValue"
					:current-page.sync="pageNum"
					background
					layout="total, sizes,prev, pager, next, jumper"
					:page-size="pageSize"
					:page-sizes="$store.getters.pageSizes"
					:total="total"
					:pager-count="9"
					@current-change="handleCurrentChange"
					@size-change="handleSizeChange"
				></el-pagination>
			</template>
		</main-content>

		<detail v-else :detailData="detailData" @goBack="goBack"></detail>
		<el-dialog
			:title="$t('common.row_set')"
			center
			:visible.sync="colSettings.visible"
			width="475px"
			:before-close="cancleSetColumn"
			class="setting-div"
		>
			<div>
				<el-link type="primary" class="mb15" @click="clickDel">
					复原缺省
				</el-link>
			</div>
			<div
				v-for="(item, index) in oldCol"
				:key="index"
				class="setting-div"
			>
				<el-checkbox v-if="index !== 0" v-model="item.isShow">
					{{ item.label }}
				</el-checkbox>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button @click="cancleSetColumn">
					{{ $t('common.cancel') }}
				</el-button>
				<el-button type="primary" @click="handleOrderList">
					{{ $t('common.submit') }}
				</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import dayjs from 'dayjs'
// import Sortable from 'sortablejs'
import list from '@/mixins/list'
import { Storage } from '@/utils/compose'
import { routerNames } from '@/utils/consts'
import summaryList from './components/summaryList'
import { getColumns } from './components/columns'
import MainContent from '@/components/MainContent/index.vue'
// const end = dayjs().endOf('day')
// const start = dayjs().startOf('day')
const endRebateTime = () => {
	return dayjs().endOf('day')
}
const startRebateTime = () => {
	return dayjs()
		.startOf('day')
		.subtract(6, 'd')
}
export default {
	name: routerNames.proxyRebateRecord,
	components: {
		detail: () => import('./components/detail'),
		MainContent
	},
	mixins: [list, summaryList],
	data() {
		return {
			tableHeight: 480,
			otherDependenComponents: [],
			queryData: { inputType: 1 },
			searchTime: [startRebateTime(), endRebateTime()],
			searchGetTime: [],
			tableData: [],
			subSummary: {},
			totalSummary: {},
			detailData: {},
			exportBtnLoading: false,
			pageType: 'i',
			merchantObj: '',
			oldCol: [],
			dropCol: [],
			newCol: [],
			proxyLevels: [],
			colSettings: {
				visible: false
			},
			// 拖拽状态
			dragState: {
				start: -3, // 起始元素的 index 防止初始化cellStyle时序号、展开等默认样式改变，最好小于-3
				end: -3, // 移动鼠标时所覆盖的元素 index
				dragging: false, // 是否正在拖动
				direction: undefined // 拖动方向
			},
			headKey: 'proxyRebateRecord', // 表头数组变换位置时，重绘table（不更新该值，表头数组变化时，页面不会改变）
			scrollX: 0 // 初始x轴scroll位置（用于定位X轴滚动条）
		}
	},
	computed: {
		withdrawOrderClientStatus() {
			return this.globalDics.rebateClientStatusList || []
		}
	},
	watch: {
		timeFlag: {
			handler(newVal) {
				this.tableData = []
				this.total = 0
			}
		},
		oldCol: {
			handler(newVal) {
				if (newVal) {
					this.newCol = newVal.filter((its) => {
						return its.isShow === true
					})
				}
			},
			deep: true
		}
	},
	created() {
		const storageColumn = this.getSaveTableData()
		this.dropCol = getColumns()
		const uu_Id = this.$store.state.user.userInfo?.id
		this.oldCol =
			storageColumn &&
			storageColumn[`${uu_Id}_commonTableKey_proxyRebateRecord`]
				? storageColumn[`${uu_Id}_commonTableKey_proxyRebateRecord`]
				: this.dropCol
		this.newCol = this.oldCol
		this.getProxyLevels()
	},
	mounted() {},
	methods: {
		forceUpdate(value) {
			this.$forceUpdate()
			this.queryData.inputValue = this.queryData.inputValue.replace(
				/[^A-Za-z0-9]/g,
				''
			)
		},
		getProxyLevels() {
			this.$api.getProxylevelnameList().then((res) => {
				this.proxyLevels = res.data || []
			})
		},
		// 鼠标摁下触发
		handleMounseDown(e, column, $index) {
			this.dragState.dragging = true
			this.dragState.start = parseInt($index - 0)
			// 添加鼠标抬起事件  消除鼠标摁下立刻松开问题
			document.addEventListener('mouseup', this.handleMouseUp)
			// 添加拖拽结束事件
			document.addEventListener('dragend', this.handleMouseUp)
			// 对选中的表头允许其拖拽
			const dragclass = '.el-table__header-wrapper .' + column.id
			const dragDom = document.querySelectorAll(dragclass)
			dragDom.forEach((dom) => {
				// 允许表头块可以被拖拽 draggable 属性 不允许拖拽dragover等相关拖拽事件无法触发
				dom.setAttribute('draggable', true)
			})
		},
		/** 鼠标在拖拽移动时触发 */
		handleDragover(e, column, $index) {
			if (this.dragState.dragging) {
				// 获取当前滚动条的位置
				const scrollDom = this.$refs.elTable.bodyWrapper
				this.scrollX = scrollDom.scrollLeft
				const index = parseInt($index - 0) // 记录起始列
				/** 实时更改鼠标处于表头的位置 */
				if (index - this.dragState.start !== 0) {
					this.dragState.direction =
						index - this.dragState.start < 0 ? 'left' : 'right' // 判断拖动方向
					this.dragState.end = parseInt($index - 0)
				} else {
					this.dragState.end = this.dragState.start
					this.dragState.direction = null
				}
			}
		},
		/** 鼠标抬起或拖拽结束触发 */
		handleMouseUp() {
			// 更新拖拽后的表头
			this.headDraged(this.dragState)
			const { end } = this.dragState
			// 初始化拖动状态
			this.dragState = {
				start: end, // 记录最后拖动的位置
				end: -9,
				dragging: false,
				direction: undefined
			}
			document.removeEventListener('mouseup', this.handleMouseUp)
			document.removeEventListener('dragend', this.handleMouseUp)
			setTimeout(() => {
				// 重置拖拽状态
				this.dragState.start = -9
			}, 500)
		},
		// 更新拖拽后的表头
		headDraged({ start, end, direction }) {
			if (direction) {
				const originColumn = this.newCol[start]
				// 有位置交换时，原先位置的元素删除，再在目标处插入
				this.oldCol.splice(start, 1)
				this.oldCol.splice(end, 0, originColumn)
				this.headKey = new Date().getTime() + '' // 更新table key值
				const uu_Id = this.$store.state.user.userInfo.id
				const uidKey = uu_Id + '_commonTableKey_proxyRebateRecord'
				const getLocalTableData = Storage.get('commonTableKey')
				if (getLocalTableData) {
					Storage.set(
						'commonTableKey',
						Object.assign(getLocalTableData, {
							[uidKey]: this.oldCol
						})
					)
				} else {
					Storage.set('commonTableKey', {
						[uidKey]: this.oldCol
					})
				}
				this.$nextTick(() => {
					// 因为表头重绘后滚动条会移到最左端初始位置，因此如果是在中间部分拖拽，还需要把滚动条在定位到该位置
					this.$refs.elTable.bodyWrapper.scrollLeft = this.scrollX
				})
			}
		},
		// 拖动虚线样式设置
		cellClassName({ columnIndex }) {
			const { start, end, direction } = this.dragState
			const target = columnIndex - 0
			if (target === start) {
				// 被移动的元素
				return 'drag_start'
			} else if (target === end) {
				// 要移动的位置
				return `drag_end_${direction}`
			}
			return ''
		},
		openDetail(row) {
			this.allowReview = row.lockAccount === this.name
			this.detailData = row
			this.pageType = 'd'
		},
		goBack() {
			this.pageType = 'i'
			this.loadData()
		},
		loadData() {
			const timeArr = this.searchTime || []
			const timeArr1 = this.searchGetTime || []
			let params = {
				...this.queryData,
				cycleStartDate: timeArr[0]
					? dayjs(timeArr[0]).format('YYYY-MM-DD')
					: undefined,
				cycleEndDate: timeArr[1]
					? dayjs(timeArr[1]).format('YYYY-MM-DD')
					: undefined,
				receiveStartDate: timeArr1[0]
					? dayjs(timeArr1[0]).format('YYYY-MM-DD')
					: undefined,
				receiveEndDate: timeArr1[1]
					? dayjs(timeArr1[1]).format('YYYY-MM-DD')
					: undefined,
				...this.getParams()
			}
			params = {
				...this.getParams(params)
			}
			if (params.inputType === 1) {
				params.proxyAccount = params.inputValue || undefined
				params.topProxyAccount = undefined
			} else if (params.inputType === 2) {
				params.proxyAccount = undefined
				params.topProxyAccount = params.inputValue || undefined
			}
			delete params.inputValue
			delete params.inputType
			this.loading = true
			this.tableData = []
			this.pageCurrency = this.merchantObj?.currency || ''
			Promise.all([
				this.$api.getProxyReBateRecordList(params).then((res) => {
					this.tableData = res?.data?.record || []
					this.total = res?.data?.totalRecord || 0
					this.subSummary = res?.data?.summary || {}
				}),
				this.$api.getProxyReBateRecordSummary(params).then((res) => {
					this.totalSummary = res?.data || {}
				})
			])
				.catch(() => {})
				.finally(() => {
					this.loading = false
				})
		},

		reset() {
			this.pageNum = 1
			this.queryData = { inputType: 1 }
			this.timeFlag = '0'
			this.merchantObj = ''
			this.searchTime = [startRebateTime(), endRebateTime()]
			this.searchGetTime = []
			this.loadData()
		},
		reloadTime() {
			this.searchTime = [startRebateTime(), endRebateTime()]
		},
		handleExportExcel() {
			const timeArr = this.searchTime || []
			const timeArr1 = this.searchGetTime || []
			let params = {
				...this.queryData,
				cycleStartDate: timeArr[0]
					? dayjs(timeArr[0]).format('YYYY-MM-DD')
					: undefined,
				cycleEndDate: timeArr[1]
					? dayjs(timeArr[1]).format('YYYY-MM-DD')
					: undefined,
				receiveStartDate: timeArr1[0]
					? dayjs(timeArr1[0]).format('YYYY-MM-DD')
					: undefined,
				receiveEndDate: timeArr1[1]
					? dayjs(timeArr1[1]).format('YYYY-MM-DD')
					: undefined
			}
			params = {
				...this.getParams(params)
			}
			if (params.inputType === 1) {
				params.proxyAccount = params.inputValue || undefined
				params.topProxyAccount = undefined
			} else if (params.inputType === 2) {
				params.proxyAccount = undefined
				params.topProxyAccount = params.inputValue || undefined
			}
			delete params.inputValue
			delete params.inputType
			this.exportBtnLoading = true
			this.exportExcelPublic({
				api: 'getProxyReBateRecordExport',
				params
			}).finally(() => {
				this.exportBtnLoading = false
			})
		},
		// 提交列设置数据
		handleOrderList() {
			this.colSettings.visible = false
			const uu_Id = this.$store.state.user.userInfo.id
			const uidKey = uu_Id + '_commonTableKey_proxyRebateRecord'
			const getLocalTableData = Storage.get('commonTableKey')
			if (getLocalTableData) {
				Storage.set(
					'commonTableKey',
					Object.assign(getLocalTableData, {
						[uidKey]: this.oldCol
					})
				)
			} else {
				Storage.set('commonTableKey', {
					[uidKey]: this.oldCol
				})
			}
		},
		// 打开列设置弹框
		openColSettings() {
			this.colSettings.visible = true
		},
		// 取消列设置
		cancleSetColumn() {
			this.colSettings.visible = false
			this.clickDel()
		},
		// 复原缺省
		clickDel() {
			this.oldCol.map((item, index) => {
				item.isShow = true
			})
		}
	}
}
</script>
<style lang="scss" scoped>
::v-deep .el-table__fixed-footer-wrapper .cell,
::v-deep .el-table__footer-wrapper .cell {
	height: 100%;
	padding: 0 !important;
	margin: 0 !important;
	> div {
		height: 100%;
	}
}
::v-deep .footer_count_row {
	min-height: 50px;
	height: 50%;
	display: flex;
	font-weight: 700;
	padding: 5px 0;
	align-items: center;
	flex-direction: column;
	justify-content: center;
}
::v-deep .footer_count_row_border {
	border-top: 1px solid #ebeef5;
}
.input-with-select {
	width: 110px;
}
</style>
